package com.cswnode.Aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author csw
 * @create 2020/9/30 19:11
 */
//统一日志管理
@Component
@Aspect
public class ServiceAspect {

    private static final Logger logger = LoggerFactory.getLogger(ServiceAspect.class);
    @Pointcut("execution(* com.cswnode.Service.*.*(..))")
    public void pointcut(){

    }
    //方法执行前切入编程
    @Before("pointcut()")
    public void before(JoinPoint joinPoint){//执行的目标对象
        //用户【IP】、在【时间】、访问了【路径，方法】
        //获得request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }

        HttpServletRequest request = attributes.getRequest();
        //获取id
        String ip = request.getRemoteHost();
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //访问的路径方法
        String target = joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName();
        logger.info(String.format("用户[%s],在[%s],访问了[%s]",ip,now,target));
    }
//    //方法执行后
//    @After("pointcut()")
//    public void after(){
//        logger.info("after");
//    }
//    //返回值以后
//    @AfterReturning("pointcut()")
//    public void afterReturning(){
//        logger.info("afterReturning");
//    }
//    //抛异常后
//    @AfterThrowing("pointcut()")
//    public void afterThrowing(){
//        logger.info("afterThrowing");
//    }
//    //方法执行前以及执行后
//    @Around("pointcut()")
//    public Object around(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{//连接点
//        System.out.println("方法执行前");
//        Object obj = proceedingJoinPoint.proceed();
//        System.out.println("方法执行后");
//        return obj;
//
//    }

}
